<template>
  <div style="overflow: auto;">
    <div v-for="(item, index ) in files" :key="index">
      <el-button type="text" @click="fileClickBtn(item,index)" :loading="list[index] ? list[index].loading : false">
        {{ item.substring( item.lastIndexOf('/') + 1) }}
      </el-button>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { getToken } from '@/utils/auth'
export default {
  props:{
    files:{
      type: Array,
      default:()=> [],
    }
  },
  data(){
    return{
      list:[],
    }
  },
  watch:{
    files:{
      immediate:true,
      handler(newVal , oldVal){
        this.list = []
        for( let i=0;i<newVal.length;i++){
          this.list.push({
            loading: false,
          })
        }
      }
    },
  },
  methods:{
    async fileClickBtn(item,index){
      try {
        if( item.includes('http')){
          this.$message({ message: '下载失败，文件路径错误', type: 'warning' })
          return
        }
        this.list[index].loading = true
        const response = await axios({
          method: 'get',
          url: process.env.VUE_APP_BASE_API + item,
          responseType: 'blob',
          headers: {
            Authorization: `Bearer ${ getToken() }`,
          },
        })
        const blob = new Blob([response.data])
        const fileName = this.getFileName(item)
        const link = document.createElement('a')
        link.href = window.URL.createObjectURL(blob)
        link.download = fileName
        document.body.appendChild(link)
        link.click()
        window.URL.revokeObjectURL(link.href)
        document.body.removeChild(link)
        this.$message({ message: '文件已开始下载', type: 'success' })
        setTimeout(() => {
          this.list[index].loading = false
        }, 400);
      } catch (error) {
        setTimeout(() => {
          this.list[index].loading = false
        }, 400);
      }
    },
    getFileName(item) {
      const result = item.substring( item.lastIndexOf('/') + 1)
      return result
    },
  },
}
</script>

<style scoped lang="scss">

</style>